<template>
  <div id="pdfWrap">
    <canvas id="theCanvas"></canvas>
  </div>
  <div class="page-nav">
    <button @click="prev">prev</button>
    <span>
      <input
      type="number"
      v-model="currentPage"
      @input="gotoSelectedPage"
      min="1"
      max="numPages"
    />{{ currentPage }}/ {{ numPages }} </span>
    <button @click="next">next</button>
  </div>
</template>

<script>
import * as pdfjsLib from "pdfjs-dist/build/pdf.min.js";
import "pdfjs-dist/web/pdf_viewer.css";

pdfjsLib.GlobalWorkerOptions.workerSrc = new URL(
  "pdfjs-dist/build/pdf.worker.min.js",
  import.meta.url
).href;

export default {
  name: "PdfViewer",
  data() {
    return {
      scale: 0.9,
      loadingTask: null,
      currentPage: 1,
      numPages: 0,
      selectedPage: 1,
    };
  },
  mounted() {
    this.getPdf();
  },
  methods: {
    async getPdf() {
      const pdfUrl =
        "http://localhost:18888/html/document/static/pdf/%E6%9C%8D%E5%8A%A1%E5%8D%8F%E8%AE%AE_20240408.pdf"; // Replace with the URL or file path of your PDF
      this.loadingTask = pdfjsLib.getDocument(pdfUrl);
      this.loadingTask.promise.then((pdf) => {
        this.numPages = pdf.numPages;
        this.renderPage(this.currentPage);
      });
    },
    renderPage(num) {
      var pdfWrap = document.getElementById("pdfWrap");
      var pageDiv = document.createElement("div");
      const canvas = document.getElementById("theCanvas");
      const context = canvas.getContext("2d");
      const dpr = window.devicePixelRatio || 1;
      const bsr =
        context.webkitBackingStorePixelRatio ||
        context.mozBackingStorePixelRatio ||
        context.msBackingStorePixelRatio ||
        context.oBackingStorePixelRatio ||
        context.backingStorePixelRatio ||
        1;
      const ratio = dpr / bsr;
      const scale = this.scale;
      // context.translate(0, 0);

      this.loadingTask.promise.then(async (pdf) => {
        const page = await pdf.getPage(num);
        const viewport = page.getViewport({ scale });
        // 准备 canvas 元素来渲染页面
        canvas.height = viewport.height;
        canvas.width = viewport.width;
        // 渲染页面到 canvas
        const renderContext = {
          canvasContext: context,
          viewport: viewport,
        };

        pageDiv.setAttribute(
          "style",
          `position: relative; height: ${canvas.height}px;  width: ${canvas.width}px; margin-bottom: 3px;`
        );
        pdfWrap.appendChild(pageDiv);
        pageDiv.appendChild(canvas);
        const pdfContainer = canvas.parentNode;

        await page.render(renderContext);
        const annotations = await page.getAnnotations();
        annotations.forEach((annotation) => {
          if (annotation.subtype === "Link" && annotation.url) {
            // 假设链接注解有一个 'url' 属性
            const rect = annotation.rect;

            const width = (rect[2] - rect[0]) * scale;
            const height = (rect[3] - rect[1]) * scale;
            const y = canvas.height - rect[1] * scale - height;
            const x = rect[0] * scale; // 根据 scale 调整位置
            // 创建一个 HTML 元素代表链接区域
            const linkDiv = document.createElement("div");
            linkDiv.style.position = "absolute";
            linkDiv.style.left = `${x}px`;
            linkDiv.style.top = `${y}px`;
            linkDiv.style.width = `${width}px`;
            linkDiv.style.height = `${height}px`;
            linkDiv.style.borderRadius = "4px";
            linkDiv.style.backgroundColor = "rgba(0, 0, 255, 0.2)"; // 或者设置为你想要的样式
            linkDiv.style.cursor = "pointer"; // 鼠标悬停时变为手型图标
            linkDiv.style.zIndex = 1000; // 确保在最上层

            // 添加点击事件监听器
            linkDiv.addEventListener("click", (event) => {
              event.preventDefault();
              window.open(annotation.url, "_blank"); // 打开链接
            });

            // 将链接 div 添加到 canvas 的父元素中
            pdfContainer.appendChild(linkDiv);
          }
        });
      });
    },
    next() {
      if (this.currentPage < this.numPages) {
        this.currentPage++;
        this.renderPage(this.currentPage);
      }
    },
    prev() {
      if (this.currentPage > 1) {
        this.currentPage--;
        this.renderPage(this.currentPage);
      }
    },
    gotoSelectedPage() {
      if (this.currentPage >= 1 && this.currentPage <= this.numPages) {
        this.renderPage(this.currentPage);
      }
    },
  },
};
</script>

<style>
div.page {
  display: inline-block;
}
</style>
